package helper

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"zong-microservice/pkg/logger"
)

// RSAEncrypt RSA加密 plainText 要加密的数据 key 公钥
func RSAEncrypt(plainText []byte, key []byte) []byte {
	//pem解码
	block, _ := pem.Decode(key)
	//x509解码
	publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	logger.LogError(err)
	//类型断言
	publicKey := publicKeyInterface.(*rsa.PublicKey)
	//对明文进行加密
	cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
	logger.LogError(err)
	//返回密文
	return cipherText
}

// RSADecrypt RSA解密 cipherText 需要解密的byte数据 key 私钥
func RSADecrypt(cipherText []byte, Key []byte) []byte {
	//pem解码
	block, _ := pem.Decode(Key)
	//X509解码
	privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		panic(err)
	}
	//对密文进行解密
	plainText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
	//返回明文
	return plainText
}
